package com.fengmang.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.smartapp.update.BatchUtils;
import com.smartapp.update.Utils;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import butterknife.BindView;
import butterknife.ButterKnife;
import dalvik.system.DexClassLoader;

public class MainActivity extends Activity {

    private Class<?> localClass;

    private Object localInstance;

    Context context;

    @BindView(R.id.tv1)
    TextView tv1;

    // 合成成功
    private static final int SUCCESS = 1;
    // 合成的APK签名和已安装的签名不一致
    private static final int FAIL_SING = -1;
    // 合成失败
    private static final int FAIL_ERROR = -2;
    // 获取源文件失败
    private static final int FAIL_GET_SOURCE = -3;
    public static final String PATH = Environment.getExternalStorageDirectory() + File.separator;
    public static final String NEW_APK_PATH = PATH + "SmartAppUpdate.apk";
    //	public static final String NEW_APK_PATH = PATH + "bsdiff_old.apk";
    public static final String PATCH_PATH = PATH + "SmartAppUpdate.patch";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        context = this;

//        Instrumentation i = new Instrumentation();
//        i.callActivityOnCreate();

        Log.e("ma===onCreate", "===");



        LinearLayout ll_table = (LinearLayout) findViewById(R.id.ll_table);
//        tv1 = (TextView) findViewById(R.id.tv1);
        TextView tv2 = (TextView) findViewById(R.id.tv2);
        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                loadAPK( "/mnt/sdcard/TestRoomA.apk", "/mnt/sdcard/");
//                loadAPK( "/data/data/com.fengmang.myapplication/app-debug.apk", "/data/data/com.fengmang.myapplication/");


//                ClassLoader localClassLoader = ClassLoader.getSystemClassLoader();
//                DexClassLoader localDexClassLoader = new DexClassLoader(dexPath, dexOutputPath, null, localClassLoader);

//                PackageInfo localPackageInfo = getPackageManager().getPackageArchiveInfo("/data/data/com.fengmang.myapplication/app-debug.apk", PackageManager.GET_ACTIVITIES);

                Log.e("tv1===onClick", "==="+PluginManager.getInstance().getPackageInfo());

                if(PluginManager.getInstance().getPackageInfo()==null){
                    Intent intent = new Intent(context, TestRoomAActivity.class);
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(context, ProxyActivity.class);
                    intent.putExtra("className", "com.fengmang.myapplication.TestRoomAActivity");
                    startActivity(intent);
                }

//                Toast.makeText(context, "4"+new B().test(), Toast.LENGTH_SHORT).show();
            }
        });

        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //        loadAPK( "/mnt/sdcard/TestRoomA.apk", "/mnt/sdcard/");
//                loadAPK( "/data/data/com.fengmang.myapplication/app-debug.apk", "/data/data/com.fengmang.myapplication/");

                Log.e("tv2===onClick", "==="+PluginManager.getInstance().getPackageInfo());

                if(PluginManager.getInstance().getPackageInfo()==null){
                    Intent intent = new Intent(context, TestRoomBActivity.class);
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(context, ProxyActivity.class);
                    intent.putExtra("className", "com.fengmang.myapplication.TestRoomBActivity");
                    startActivity(intent);
                }

            }
        });



    }


    @Override
    public Resources getResources() {
        return super.getResources();

//        Log.e("getResources===0", "===");

//        try {
//
//            ClassLoader localClassLoader = ClassLoader.getSystemClassLoader();
//            DexClassLoader localDexClassLoader = new DexClassLoader("/data/data/com.fengmang.myapplication/app-debug.apk", "/data/data/com.fengmang.myapplication/", null, localClassLoader);
//
//            Class<?> localClass2 = localDexClassLoader.loadClass("com.fengmang.myapplication.RoundImageView");
//            Constructor<?> localConstructor2 = localClass2.getConstructor(new Class[] {Context.class});
//            localConstructor2.newInstance(new Object[] {this});
//
//        } catch (Exception e) {
//            Log.e("getResources===e", "==="+e);
//            e.printStackTrace();
//        }
//
//        Log.e("getResources===1", "===");

//        Log.e("ma===getResources===", super.getResources()+"==="+PluginManager.getInstance()+"==="+PluginManager.getInstance().getResources());
//        return PluginManager.getInstance().getResources()==null?super.getResources():PluginManager.getInstance().getResources();
    }

    private void loadAPK(String dexPath, String dexOutputPath) {

        try {

            ClassLoader localClassLoader = ClassLoader.getSystemClassLoader();
            DexClassLoader localDexClassLoader = new DexClassLoader(dexPath, dexOutputPath, null, localClassLoader);

            PackageInfo localPackageInfo = getPackageManager().getPackageArchiveInfo(dexPath, PackageManager.GET_ACTIVITIES);

            if ((localPackageInfo.activities != null) && (localPackageInfo.activities.length > 0)) {

//                String activityName = localPackageInfo.activities[0].name;
                String activityName = "com.fengmang.myapplication.TestRoomAActivity";

                localClass = localDexClassLoader.loadClass(activityName);
                Constructor<?> localConstructor = localClass.getConstructor(new Class[] {Context.class});
                localInstance = localConstructor.newInstance(new Object[] {this});

                Log.e("loadAPK===1", localClass+"==="+localInstance);



//                AssetManager manager = AssetManager.class.newInstance();
//                Method addAssetPath = AssetManager.class.getMethod("addAssetPath", String.class);
//                addAssetPath.invoke(manager, dexPath);
//                resources = new Resources(manager, getResources().getDisplayMetrics(), getResources().getConfiguration());

                Log.e("loadAPK===2", localClass+"==="+localInstance);

//                Method getResourcesMethod = localClass.getDeclaredMethod("getResources", null);
//                getResourcesMethod.setAccessible(true);
//                getResourcesMethod.invoke(localInstance, null);
//
//                Log.e("loadAPK===2", localClass+"==="+localInstance);

                Class<?> localClass2 = localDexClassLoader.loadClass("com.fengmang.myapplication.RoundImageView");
                Constructor<?> localConstructor2 = localClass2.getConstructor(new Class[] {Context.class});
                localConstructor2.newInstance(new Object[] {this});

                Log.e("loadAPK===3", localClass+"==="+localInstance);



//                Class<?> layout = localDexClassLoader.loadClass("com.fengmang.myapplication.R$layout");
//                Field field = layout.getField("activity_main2");
//                Integer obj = (Integer) field.get(null);
                int obj = getResources().getIdentifier("activity_main2", "layout", getPackageName());
//                View view = LayoutInflater.from(this).inflate(getResources().getLayout(obj),null);
                // 或者这样，但一定要重写getResources方法，才能这样写
                View view = LayoutInflater.from(this).inflate(obj, null);
                Method method = localClass.getDeclaredMethod("setLayout", View.class);
                method.setAccessible(true);
                method.invoke(localInstance, view);

                Log.e("loadAPK===4", localClass+"==="+localInstance);


                Method onCreateMethod = localClass.getDeclaredMethod("onCreate", new Class[] {Bundle.class});
                onCreateMethod.setAccessible(true);
                onCreateMethod.invoke(localInstance, new Object[] {null});

                Log.e("loadAPK===5", localClass+"==="+localInstance);
            }

        } catch (Exception e) {
            Log.e("loadAPK===e", "==="+e);
            e.printStackTrace();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}